package com.qf.hytrix.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.qf.common.vo.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CountDownLatch;

@RestController
public class TestController {

    @GetMapping("/test3/{num}")
    public R test3(@PathVariable("num") Integer num) throws InterruptedException {

        RestTemplate restTemplate = new RestTemplate();

        // 创建一个 倒计时器对象 ，该对象可以用于协调线程
        CountDownLatch countDownLatch = new CountDownLatch(num);
        // 循环 num 次，调用/test2接口
        for (int i = 0; i < num; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String result = restTemplate.getForObject("http://localhost:9300/test2", String.class);
                    System.out.println(Thread.currentThread().getName()+":收到了响应结果："+result);
                    countDownLatch.countDown();
                }
            }).start();
        }

        // 让当前线程在countDownLatch对象上等待,直到计数器的值归零后才可以继续向下运行
        countDownLatch.await();

        return R.ok("请求发送完毕");

    }

    @HystrixCommand(fallbackMethod = "test2fallback",
            threadPoolKey = "mypool",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "5"),
                    @HystrixProperty(name = "maxQueueSize", value = "5")
            })
    @GetMapping("/test2")
    public R test2() throws InterruptedException {

        System.out.println("处理请求的线程的名字为:"+Thread.currentThread().getName());

        Thread.sleep(1000);

        return R.ok("test2");
    }

    public R test2fallback(){
        return R.ok("test2降级了");
    }


    @HystrixCommand(fallbackMethod = "test1fallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "2000"),
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "70"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "5000")
    })
    @GetMapping("/test1")
    public R test1(Integer flag) throws InterruptedException {
        System.out.println("进入业务方法了");
        if (flag==1){
            Thread.sleep(3000);
        }else if(flag==2){
            int a = 10/0;
        }

        return R.ok("test1");
    }

    // 该方法是test1的降级方法
    public R test1fallback(Integer flag){
        return R.ok("降级了");
    }

}
